import React from 'react';
import { List, Form, Input, Button, notification as Notification, Space } from 'antd';

import './BookSearch.scss';
import { listBookInfo } from '../../../api/bookInfo';
import { FormInstance } from 'antd/lib/form';
import Highlighter from 'react-highlight-words';

class BookSearch extends React.Component {
  state = {
    listData: [],
    searchTexts: []
  };
  formRef = React.createRef(FormInstance);

  constructor(props) {
    super(props);
    this.state = {
      listData: [],
      searchTexts: []
    };
  }

  componentDidMount() {
    this.getListData();
  }

  getListData = (pageNum = 0, pageSize = 10, bookInfo) => {
    bookInfo = bookInfo || {
      sortField: 'create_time',
      order: 'desc'
    };

    listBookInfo(pageNum, pageSize, bookInfo).then(({ data }) => {
      console.log(data, typeof data, 'data');
      const { list } = data;
      console.log(list[0], typeof list[0], 'list[0]');
      this.setState({
        listData: list
      });
    }).catch((e) => {
      console.log(e, typeof e, 'listBookInfo e');
    });
  };

  onSearch = (e) => {
    this.formRef.current.validateFields().then((values) => {
      const { isbn, name } = values;
      console.log(isbn, typeof isbn, 'isbn');
      console.log(name, typeof name, 'name');

      const searchTexts = [];
      if (isbn) {
        searchTexts.push(isbn + '');
      }
      if (name) {
        searchTexts.push(name + '');
      }
      this.setState({
        searchTexts
      });
      this.getListData(0, 0, { isbn, name });
    }).catch((errorInfo) => {

      /*
      errorInfo:
      {
        values: {
          username: 'username',
          password: 'password',
        },
        errorFields: [
          { password: ['username'], errors: ['Please input your Password!'] },
        ],
        outOfDate: false,
      }
      */
      const { errorFields } = errorInfo;
      Notification.error({
        message: errorFields[0].errors[0],
        duration: 2
        // description: errorFields[0].errors[0]
      });
    });
    e.preventDefault();
  };

  onReset = () => {
    this.formRef.current.resetFields();
  };

  highlighter = (text) => {
    const { searchTexts } = this.state;
    return searchTexts.length > 0 ? (
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={searchTexts}
        autoEscape
        textToHighlight={text ? text.toString() : ''}
      />
    ) : (text);
  };

  render() {
    const { listData } = this.state;

    const renderItem = (item) => (
      <List.Item
        className="book-list-item"
        key={item.isbn}
        extra={
          <img
            width={200}
            alt="logo"
            src={'http://localhost:8077/bookSharing/common/image?fileName=' + item.coverImage}
          />
        }
      >
        <List.Item.Meta
          title={
            <div className="list-item-title">
              <a href={item.id}>{this.highlighter(item.name)}</a>
              <span className="item-isbn">ISBN: {this.highlighter(item.isbn)}</span>
            </div>
          }
          description={item.description}
        />
        <pre className="content">{item.desc}</pre>
        <div className="footer">
          <span>分享者：<a className="owner-name" href={item.ownerUserId}>{item.ownerUserName}</a></span>
          <span className="date">{item.createTime}</span>
        </div>
      </List.Item>
    );

    return (
      <div className="book-search-container">
        <div className="search-warp">
          <Form
            ref={this.formRef}
            name="horizontal_login"
            layout="inline">
            <Form.Item
              name="isbn"
            >
              <Input placeholder="ISBN"/>
            </Form.Item>
            <Form.Item
              name="name"
            >
              <Input placeholder="书名"/>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  block
                  onClick={this.onSearch}
                >
                  查找
                </Button>
                <Button
                  type="primary"
                  block
                  onClick={this.onReset}
                >
                  清空
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
        <List
          itemLayout="vertical"
          dataSource={listData}
          renderItem={renderItem}
        />
      </div>
    );
  }
}

export default BookSearch;
